var areaCache = null, defaultParent = "0", deletedAreas = new Array();
var entname = $("#entname"), buslicenseno = $("#buslicenseno"), leader = $("#leader"), contactnumber = $("#contactnumber");
var provinceid = $("#provinceid"), cityid = $("#cityid"), districtid = $("#districtid"), streetid = $("#streetid"), detailaddr = $("#detailaddr");
var provinceidSelector = $("#provinceidSelector"), cityidSelector = $("#cityidSelector"), districtidSelector = $("#districtidSelector"), streetidSelector = $("#streetidSelector");
var buslicense = $("#buslicense"), folicense = $("#folicense"), testreport = $("#testreport"), qualityreport = $("#qualityreport");
var buslicenseImg = $("#buslicenseImg"), folicenseImg = $("#folicenseImg"), testreportImg = $("#testreportImg"), qualityreportImg = $("#qualityreportImg");
var buslicenseSelector = $("#buslicenseSelector"), folicenseSelector = $("#folicenseSelector"), testreportSelector = $("#testreportSelector"), qualityreportSelector = $("#qualityreportSelector");

$(function() {
	mobileGlobal.sendRequest(__mobilectx + "/supplier/loadSupplierData.xhtml", null, null, function(data, status) {
		if (data.status) {
			$("input[prop='fileInput']").change(onFileInputChanged);
			$("input[prop='fileSelector']").click(onFileSelectorClick);
			$("input[prop='areaSelector']").click(onAreaSelectorClick);
			
			areaCache = data.result.areas;
			
			var supplier = data.result.supplier;
			entname.val(supplier.entname);
			buslicenseno.val(supplier.buslicenseno);
			leader.val(supplier.leader);
			contactnumber.val(supplier.contactnumber);
			provinceid.val(supplier.provinceid);
			provinceidSelector.val(supplier.pareaname);
			cityid.val(supplier.cityid);
			cityidSelector.val(supplier.careaname);
			districtid.val(supplier.districtid);
			districtidSelector.val(supplier.dareaname);
			streetid.val(supplier.streetid);
			streetidSelector.val(supplier.sareaname);
			detailaddr.val(supplier.detailaddr);
			buslicenseImg.attr("src", supplier.buslicense);
			folicenseImg.attr("src", supplier.folicense);
			if (supplier.testreport) testreportImg.attr("src", supplier.testreport);
			if (supplier.qualityreport) qualityreportImg.attr("src", supplier.qualityreport);
			
			var dareas = data.result.dareas;
			for (var i = 0; i < dareas.length; i ++) {
				addNewAreaRow(i + 1, null, dareas[i], false);
			}
			addNewAreaRow(dareas.length + 1, null, null, false);
			
			mobileGlobal.hideLoading();
		} else {
			mobileGlobal.hideLoading();
			mobileGlobal.failed("加载数据失败");
		}
	});
});

//文件输入框变化事件
function onFileInputChanged(e) {
	var file = e.currentTarget.files[0], fileid = e.currentTarget.id;
	if (!/^.+\.(jpg)|(jpeg)|(png)$/.test(file.name)) {
		mobileGlobal.message("请选择图片文件");
		return;
	}
	
	switch (fileid) {
		case "buslicense":
			buslicenseSelector.val(file.name);
			break;
		case "folicense":
			folicenseSelector.val(file.name);
			break;
		case "testreport":
			testreportSelector.val(file.name);
			break;
		case "qualityreport":
			qualityreportSelector.val(file.name);
			break;
	}
}

//文件选择框点击事件
function onFileSelectorClick() {
	var selectorId = $(this).attr("id");
	switch (selectorId) {
		case "buslicenseSelector":
			buslicense.click();
			break;
		case "folicenseSelector":
			folicense.click();
			break;
		case "testreportSelector":
			testreport.click();
			break;
		case "qualityreportSelector":
			qualityreport.click();
			break;
	}
}

//区域选择框点击事件
function onAreaSelectorClick() {
	var selector = $(this), selectorId = selector.attr("id"), selectorTitle = null, defaultValue = null, selectorData = null;
	
	var pvid = null, valueid = null;
	if (selectorId.startsWith("provinceid")) {
		valueid = "provinceid";
		selectorTitle = "请选择省份";
	} else if (selectorId.startsWith("cityid")) {
		pvid = "provinceid";
		valueid = "cityid";
		selectorTitle = "请选择城市";
	} else if (selectorId.startsWith("districtid")) {
		pvid = "cityid";
		valueid = "districtid";
		selectorTitle = "请选择区县";
	} else if (selectorId.startsWith("streetid")) {
		pvid = "districtid";
		valueid = "streetid";
		selectorTitle = "请选择街道";
	} else return;
	
	var parent = null, rowid = selector.parent().attr("rowid");
	if (pvid == null) parent = defaultParent;
	else parent = $("#" + pvid + rowid).val();
	if (!parent) {
		mobileGlobal.message("请先选择上级区域");
		return;
	}
	
	defaultValue = $("#" + valueid + rowid).val();
	selectorData = areaCache[parent];
	if (!selectorData) {
		queryAreas(parent, selectorId, selectorTitle, defaultValue);
		return;
	}
	
	openAreaSelector(selectorId, selectorTitle, defaultValue, selectorData);
}

//查询区域
function queryAreas(parent, selectorId, selectorTitle, defaultValue) {
	var areaKey = defaultParent, data = null;
	if (parent && parent != defaultParent) {
		areaKey = parent;
		data = {parent : parent};
	}
	
	mobileGlobal.sendRequest(__ctx + "/nr/getAreasForSelect.xhtml", data, null, function(data, status) {
		mobileGlobal.hideLoading();
		if (data.status) {
			areaCache[areaKey] = data.result;
			if (selectorId) openAreaSelector(selectorId, selectorTitle, defaultValue, data.result);
		}
	});
}

//打开区域选择器
function openAreaSelector(id, title, value, data) {
	if (!data || !Array.isArray(data) || data.length == 0) {
		mobileGlobal.message("未找到任何区域");
		return;
	}
	
	var defaultValue = (value) ? [value] : [data[0].value];
	weui.picker(data, {
		id : id, 
		title : title, 
		defaultValue : defaultValue, 
		onConfirm : function(result) {
			onAreaSelected(this.id, result[0]);
		}
	});
}

//区域选择事件
function onAreaSelected(selectorId, selectedObject) {
	var selector = $("#" + selectorId), rowid = selector.parent().attr("rowid");
	
	var valueid = null, children = null;
	if (selectorId.startsWith("provinceid")) {
		valueid = "provinceid";
		children = ["cityid", "districtid", "streetid"];
	} else if (selectorId.startsWith("cityid")) {
		valueid = "cityid";
		children = ["districtid", "streetid"];
	} else if (selectorId.startsWith("districtid")) {
		valueid = "districtid";
		children = ["streetid"];
	} else if (selectorId.startsWith("streetid")) {
		valueid = "streetid";
	} else return;
	
	var valuer = $("#" + valueid + rowid);
	if (valuer.val() != selectedObject.value) {
		valuer.val(selectedObject.value);
		selector.val(selectedObject.label);
		
		if (children == null) return;
		
		for (var index = 0; index < children.length; index ++) {
			var child = children[index];
			$("#" + child + rowid).val("");
			$("#" + child + "Selector" + rowid).val("");
		}
		
		if (!areaCache[selectedObject.value]) queryAreas(selectedObject.value);
	}
}

//操作按钮点击事件
function onOperatorClick(obj) {
	var operator = $(obj);
	
	if (operator.hasClass("fa-plus-square")) {
		operator.removeClass("fa-plus-square").addClass("fa-minus-square");
		
		var parent = operator.parent(), rowid = parseInt(parent.attr("rowid")) + 1;
		addNewAreaRow(rowid, parent, null, true);
	} else {
		mobileGlobal.openConfirmDialog("确定要删除配送区域？", function() {
			mobileGlobal.closeConfirmDialog();
			
			var areaRow = operator.parent(), entityid = areaRow.attr("data-id");
			if (entityid) {
				var areaInputs = areaRow.find("input[type='hidden']");
				var provinceidValue = null, cityidValue = null, districtidValue = null, streetidValue = null;
				
				for (var i = 0; i < areaInputs.length; i ++) {
					var areaInput = $(areaInputs[i]), areaInputId = areaInput.attr("id");
					if (areaInputId.startsWith("provinceid")) {
						provinceidValue = areaInput.val();
					} else if (areaInputId.startsWith("cityid")) {
						cityidValue = areaInput.val();
					} else if (areaInputId.startsWith("districtid")) {
						districtidValue = areaInput.val();
					} else if (areaInputId.startsWith("streetid")) {
						streetidValue = areaInput.val();
					}
				}
				
				var area = {entityid : entityid, 
							provinceid : provinceidValue, 
							cityid : cityidValue, 
							districtid : districtidValue, 
							streetid : streetidValue, 
							deleteflag : true};
				deletedAreas.push(area);
			}
			areaRow.parent().remove();
		});
	}
}

//添加新区域行
function addNewAreaRow(rowid, before, valobj, scroll) {
	var html = "<div class='row'><div prop='areaRow' rowid='" + rowid + "'>" + 
				"<input id='provinceid" + rowid + "' type='hidden'/>" + 
				"<input id='provinceidSelector" + rowid + "' class='weui-input input area multiple' type='text' readonly='readonly' prop='areaSelector' placeholder='省'/>" + 
				"<input id='cityid" + rowid + "' type='hidden'/>" + 
				"<input id='cityidSelector" + rowid + "' class='weui-input input area multiple' type='text' readonly='readonly' prop='areaSelector' placeholder='市'/>" + 
				"<input id='districtid" + rowid + "' type='hidden'/>" + 
				"<input id='districtidSelector" + rowid + "' class='weui-input input area multiple' type='text' readonly='readonly' prop='areaSelector' placeholder='区县'/>" + 
				"<input id='streetid" + rowid + "' type='hidden'/>" + 
				"<input id='streetidSelector" + rowid + "' class='weui-input input area multiple' type='text' readonly='readonly' prop='areaSelector' placeholder='街道'/>" + 
				"<i class='fa fa-plus-square operator' onclick='onOperatorClick(this);'></i>" + 
			   "</div></div>";
	var append = $(html);
	append.find("input[prop='areaSelector']").click(onAreaSelectorClick);
	
	if (valobj) {
		append.attr("data-id", valobj.entityid);
		append.find("input[id='provinceid" + rowid + "']").val(valobj.provinceid);
		append.find("input[id='provinceidSelector" + rowid + "']").val(valobj.pareaname);
		append.find("input[id='cityid" + rowid + "']").val(valobj.cityid);
		append.find("input[id='cityidSelector" + rowid + "']").val(valobj.careaname);
		append.find("input[id='districtid" + rowid + "']").val(valobj.districtid);
		append.find("input[id='districtidSelector" + rowid + "']").val(valobj.dareaname);
		append.find("input[id='streetid" + rowid + "']").val(valobj.streetid);
		append.find("input[id='streetidSelector" + rowid + "']").val(valobj.sareaname);
		append.find("i").removeClass("fa-plus-square").addClass("fa-minus-square");
	}
	
	if (before) before.parent().after(append);
	else $(".weui-cells_input").append(append);
	
	if (scroll) {
		var contentHeight = $(".weui-cells_input").get(0).scrollHeight;
		$(".weui-cells_input").get(0).scrollTop = contentHeight;
	}
}

//返回按钮点击事件
function onBackClick() {
	mobileGlobal.backword();
}

//提交按钮点击事件
function onSubmitClick() {
	var formData = new FormData();
	
	//基本信息
	formData.append("entname", entname.val());
	formData.append("buslicenseno", buslicenseno.val());
	if (buslicense[0].files[0]) formData.append("buslicense", buslicense[0].files[0]);
	formData.append("leader", leader.val());
	formData.append("contactnumber", contactnumber.val());
	formData.append("provinceid", provinceid.val());
	formData.append("cityid", cityid.val());
	formData.append("districtid", districtid.val());
	formData.append("streetid", streetid.val());
	formData.append("detailaddr", detailaddr.val());
	if (folicense[0].files[0]) formData.append("folicense", folicense[0].files[0]);
	if (testreport[0].files[0]) formData.append("testreport", testreport[0].files[0]);
	if (qualityreport[0].files[0]) formData.append("qualityreport", qualityreport[0].files[0]);
	
	//配送区域
	var areaRows = $("div[prop='areaRow']"), distributionareas = 0, ignoreIndexs = new Array(), deletedCount = 0;
	for (var i = 0; i < areaRows.length; i ++) {
		var areaRow = $(areaRows[i]), areaInputs = areaRow.find("input[type='hidden']"), entityidValue = areaRow.attr("data-id");
		var provinceidValue = null, cityidValue = null, districtidValue = null, streetidValue = null;
		
		for (var j = 0; j < areaInputs.length; j ++) {
			var areaInput = $(areaInputs[j]), areaInputId = areaInput.attr("id");
			if (areaInputId.startsWith("provinceid")) {
				provinceidValue = areaInput.val();
			} else if (areaInputId.startsWith("cityid")) {
				cityidValue = areaInput.val();
			} else if (areaInputId.startsWith("districtid")) {
				districtidValue = areaInput.val();
			} else if (areaInputId.startsWith("streetid")) {
				streetidValue = areaInput.val();
			}
		}
		
		if (!streetidValue) continue;
		
		if (!entityidValue) {
			for (var k = 0; k < deletedAreas.length; k ++) {
				if (ignoreIndexs.indexOf(k) >= 0) continue;
				
				var deletedArea = deletedAreas[k];
				if (provinceidValue === deletedArea.provinceid && 
					cityidValue === deletedArea.cityid && 
					districtidValue === deletedArea.districtid && 
					streetidValue === deletedArea.streetid) {
					entityidValue = deletedArea.entityid;
					ignoreIndexs.push(k);
					break;
				}
			}
		}
		
		if (entityidValue) formData.append("distributionareas[" + distributionareas + "].entityid", entityidValue);
		formData.append("distributionareas[" + distributionareas + "].provinceid", provinceidValue);
		formData.append("distributionareas[" + distributionareas + "].cityid", cityidValue);
		formData.append("distributionareas[" + distributionareas + "].districtid", districtidValue);
		formData.append("distributionareas[" + distributionareas + "].streetid", streetidValue);
		formData.append("distributionareas[" + distributionareas + "].deleteflag", false);
		distributionareas ++;
	}
	for (var l = 0; l < deletedAreas.length; l ++) {
		if (ignoreIndexs.indexOf(l) >= 0) continue;
		
		formData.append("distributionareas[" + distributionareas + "].entityid", deletedAreas[l].entityid);
		formData.append("distributionareas[" + distributionareas + "].deleteflag", true);
		distributionareas ++;
		deletedCount ++;
	}
	
	if (!formData.get("entname")) {
		mobileGlobal.message("企业名称必须填写");
		return;
	}
	if (!formData.get("buslicenseno")) {
		mobileGlobal.message("营业执照号必须填写");
		return;
	}
	if (!formData.get("leader")) {
		mobileGlobal.message("负责人必须填写");
		return;
	}
	if (!/^1[3456789]\d{9}$/.test(formData.get("contactnumber"))) {
		mobileGlobal.message("联系电话必须填写且为有效手机号");
		return;
	}
	if (!formData.get("streetid")) {
		mobileGlobal.message("所在区域必须填写");
		return;
	}
	if (!formData.get("detailaddr")) {
		mobileGlobal.message("详细地址必须填写");
		return;
	}
	if ((distributionareas - deletedCount) <= 0) {
		mobileGlobal.message("配送区域必须设置");
		return;
	}
	
	mobileGlobal.loading("正在提交数据，请稍后...");
	
	$.ajax({
		url : __mobilectx + "/supplier/resubmitSupplier.xhtml", 
		data : formData, 
		contentType : false, 
		processData : false, 
		success : function(data, status) {
			mobileGlobal.hideLoading();
			if (data.status) {
				mobileGlobal.openMessageDialog("提交资料成功！", function() {
					mobileGlobal.closeMessageDialog();
					mobileGlobal.backword();
				});
			} else {
				mobileGlobal.openMessageDialog(data.result, function() {
					mobileGlobal.closeMessageDialog();
				});
			}
		}, 
		error : function(xhr, msg, e) {
			mobileGlobal.hideLoading();
			mobileGlobal.openMessageDialog("网络请求错误！", function() {
				mobileGlobal.closeMessageDialog();
			});
		}
	});
}